package com.zl.csMall.util;

import com.alibaba.fastjson2.JSONObject;
import com.zl.csMall.code.constant.EntiretyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @description: 微信小程序工具类
 * @author: ChenNing
 * @date 2025-10-22 15:44
 */
@Slf4j
@Component
public class WechatUtil {

    @Value("${WECHATT.MINI-PROGRAM-USER.APPID}")
    private String APPID;
    @Value("${WECHATT.MINI-PROGRAM-USER.SECRET}")
    private String SECRET;
    @Autowired
    private RestTemplate restTemplate;


    /**
     * @description: 获取小程序openId
     * @param code 小程序生成
     * @return: 小程序账号唯一标识openId
     * @author ChenNing
     * @date: 2025-10-22 15:46
     */
    public String getOpenId(String code){
        String url = EntiretyConstant.Wechat.GET_OPENID_URL;
        url += "?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String result = restTemplate.getForObject(url, String.class);
        HashMap<String, String> resultMap = JSONObject.parseObject(result, HashMap.class);
        log.info("ZL - CHENNING【获取小程序openId】 小程序请求openId接口:" + url);
        log.info("ZL - CHENNING【获取小程序openId】 小程序请求openId返回:" + result);

        if (resultMap != null && resultMap.get("openid") != null){
            return resultMap.get("openid").toString();
        } else {
            log.error("ZL - CHENNING【获取小程序openId】小程序请求openId接口：" + url);
            log.error("ZL - CHENNING【获取小程序openId】小程序请求openId返回：" + result);
        }
        return null;
    }

}
